import { loginUser, getUserInfo } from '@/api/user'

const state = () => {
  return {
    // 存储用户的token值
    token: '',
    // 存储用户基本信息
    userInfo: {
      nickname: ''
    }
  }
}

const mutations = {
  // 设置token
  SET_TOKEN (state, token) {
    state.token = token
  },
  // 设置用户
  SET_USER (state, user) {
    state.userInfo = user
  }
}

const actions = {
  // 用户登录
  async loginActions (context, userInfo) {
    const res = await loginUser(userInfo)
    // 登录成功
    if (res.code === 0) {
      context.commit('SET_TOKEN', res.data)
    }
    return res
  },

  // 获取用户的个人信息
  async userInfoActions (context) {
    const res = await getUserInfo()
    context.commit('SET_USER', res.data)
  },

  // 退出登录
  logoutActions (context) {
    context.commit('SET_TOKEN', '')
    context.commit('SET_USER', {})
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
